#!/bin/bash
# Mallards Print Agent launcher.
#
# Runs when the user double-clicks the .app. Responsibilities:
#   1. First run: prompt the user for the 8-char pairing code via a
#      native Mac dialog, pair, write config.
#   2. Always: install/refresh a LaunchAgent so the daemon runs on every
#      login from here on out.
#   3. Hand off — the LaunchAgent supervises the daemon; we exit.
set -e

BUNDLE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BINARY="$BUNDLE_DIR/MacOS/mallards-print-agent"
PLIST_TEMPLATE="$BUNDLE_DIR/Resources/com.mallardsrebates.print-agent.plist"
LABEL="com.mallardsrebates.print-agent"
PLIST_DST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG_FILE="$HOME/Library/Logs/mallards-print-agent.log"
CONFIG_DIR="$HOME/Library/Application Support/mallards-rebates-print-agent"
CONFIG_FILE="$CONFIG_DIR/config.json"

mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"

# -------- First-run pairing --------
if [ ! -f "$CONFIG_FILE" ]; then
  # Ask the user for the pairing code via AppleScript.
  CODE=$(osascript <<EOF
try
    set theResponse to (display dialog "Enter the 8-character pairing code from your iPhone.

Open Mallards → Settings (⚙) → Print Agent → Generate Code." default answer "" with title "Pair Mallards Print Agent" with icon note buttons {"Cancel", "Pair"} default button "Pair")
    text returned of theResponse
on error number -128
    return ""
end try
EOF
)

  if [ -z "$CODE" ]; then
    osascript -e 'display notification "Pairing cancelled. Open Mallards Print Agent again when you have a code." with title "Mallards Print Agent"' 2>/dev/null || true
    exit 0
  fi

  # Pair non-interactively. Binary writes config on success.
  if ! "$BINARY" -pair "$CODE" >>"$LOG_FILE" 2>&1; then
    osascript <<EOF
display dialog "Pairing failed. Check that the code was entered correctly and that your iPhone is online.

Details are in:
$LOG_FILE" with title "Mallards Print Agent" with icon caution buttons {"OK"} default button "OK"
EOF
    exit 1
  fi
fi

# -------- Install / refresh the LaunchAgent --------
# Render plist with absolute paths to this bundle's binary.
sed "s|__BINARY_PATH__|$BINARY|g; s|__LOG_PATH__|$LOG_FILE|g" \
  "$PLIST_TEMPLATE" > "$PLIST_DST"

# Reload silently. Stop cleanly if already running, then start.
launchctl unload "$PLIST_DST" 2>/dev/null || true
launchctl load "$PLIST_DST"

# Friendly success toast.
osascript -e 'display notification "Running in the background. Tap SEND TO AGENT on any receipt in the app to print." with title "Mallards Print Agent" sound name "Glass"' 2>/dev/null || true

exit 0
